/**
 * @file 面包屑
 * @author lizhaoxia(lizhaoxia@baijia.com)
 * @date 2019-07-08
 */

import {Link} from 'react-router-dom';
import {connect} from 'react-redux';
import PropTypes from 'prop-types';
import {Breadcrumb} from 'antd';

const {Item} = Breadcrumb;

const BreadcrumbComponent = props => {
    let {match, route} = props;
    const {params} = match;

    const breadItems = [];

    while (route) {
        let {title, path, super: superRoute} = route;

        // 将动态路由替换为最终路由
        if (params) {
            Object.keys(params).forEach(key => {
                path = path.replace(`:${key}`, params[key]);
            });
        }

        breadItems.push({
            title,
            href: path
        });

        route = superRoute;
    }

    return (
        <Breadcrumb>
            {breadItems.reverse().map(({title, href}) => (
                <Item key={href}>
                    <Link to={href}>
                        {title}
                    </Link>
                </Item>
            ))}
        </Breadcrumb>
    );
};

BreadcrumbComponent.propTypes = {
    match: PropTypes.shape().isRequired,
    route: PropTypes.shape().isRequired
};

export default connect(s => s)(BreadcrumbComponent);
